package com.weixin.servlet.impl;

import com.weixin.bean.Fans;
import com.weixin.bean.FansBean;
import com.weixin.bean.FansExample;
import com.weixin.dao.FansMapper;
import com.weixin.servlet.IFansServlet;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * Created by Administrator on 2018-02-06.
 */
public class FansServletImpl implements IFansServlet {

    @Autowired
    private FansMapper fansDao ;

    /**
     * 更新数据库中粉丝列表
     *
     * @param bean
     * @return
     */
    @Override
    public Integer saveFansList(FansBean bean) {
        rushFansList(bean.getData().get("openid"),getFansList());
        return null;
    }

    @Override
    public List getFansList() {
        FansExample fansExample = new FansExample();
        List<Fans> list = fansDao.selectByExample(fansExample);
        return list;
    }

    /**1，取出数据库中粉丝列表
     * 2，查出微信服务端给出粉丝列表
     * 3，查出两端不同数据
     * 4，新增的插入
     * 5，减少的修改状态
     *
     *
     *
     */
    private void rushFansList(List<String> newFansList,List<Fans> fansList){

        List<Fans> addFansList = new ArrayList<Fans>();
        List<Fans> removeFansList = new ArrayList<Fans>();
        Map<String,Integer> map = new HashMap<String,Integer>();
        for (String string : newFansList) {
            map.put(string, 1);
        }
        for (Fans fans : fansList) {
            if(map.get(fans.getOpenid())!=null)
            {
                map.put(fans.getOpenid(), 2);
                continue;
            }
            fans.setStatus(0);
            fans.setUnsubstatus(new Date().getTime());
            removeFansList.add(fans);
        }
        for(Map.Entry<String, Integer> entry:map.entrySet())
        {
            if(entry.getValue()==1)
            {
                Fans fans = new Fans();
                fans.setOpenid(entry.getKey());
                fans.setStatus(1);
                fans.setSubstatus(new Date().getTime());
                addFansList.add(fans);
            }
        }

       Integer addCount =  fansDao.insertNewFansList(addFansList);
        Integer removeCount = fansDao.updataByFansList(removeFansList);

    }

}
